#include "headers/http_post_stream.hpp"

//----------------------------------------------------------------------------------------

HttpPostStream::HttpPostStream(const QString & uploadFile, const QByteArray & _startRequest,
        const QByteArray & _endRequest, QObject * parent) : QIODevice(parent)
{
    file = new QFile(uploadFile, this);
    startRequest = new QByteArray(_startRequest);
    endRequest = new QByteArray(_endRequest);
    position = 0;
}

//----------------------------------------------------------------------------------------

HttpPostStream::~HttpPostStream()
{
    delete startRequest;
    delete endRequest;
}

//---------------------------------------------------------------------------------------

qint64 HttpPostStream::readData(char * data, qint64 maxLength)
{
    qint64 atEnd = 0;

    if (!file->isOpen())
    {
        return -1;
    }

    if (position < startRequest->size() && maxLength > 0)
    {
        qint64 count = qMin(maxLength, (qint64)startRequest->size());
        memcpy(data, startRequest->data(), count);
        data += count;

        position += count;
        atEnd += count;
        maxLength -= count;
    }

    if (maxLength > 0 && position < size())
    {
        qint64 count = qMin(maxLength, file->bytesAvailable());
        int size = file->read(data, count);
        data += size;

        maxLength -= size;
        position += size;
        atEnd += size;
    }

    if (position >= sizePart() && maxLength > 0 && position < size())
    {
        qint64 count = qMin(maxLength, (qint64)endRequest->size());
        memcpy(data, endRequest->data(), count);

        position += count;
        atEnd += count;
    }

    return atEnd;
}

//---------------------------------------------------------------------------------------

qint64 HttpPostStream::writeData(const char *, qint64)
{
    return -1;
}

//---------------------------------------------------------------------------------------

qint64 HttpPostStream::size() const
{
    return startRequest->size() + file->size() + endRequest->size();
}

//---------------------------------------------------------------------------------------

bool HttpPostStream::openFile()
{
    if (file->open(QIODevice::ReadOnly))
    {
        return this->open(QIODevice::ReadOnly);
    }

    return false;
}

//---------------------------------------------------------------------------------------

qint64 HttpPostStream::sizePart() const
{
    return startRequest->size() + file->size();
}
